import React, { useState, useEffect, useRef, useMemo } from "react";
import io, { Socket } from 'socket.io-client';
import { Input } from 'antd-mobile';
import { useLocation } from "react-router-dom";
import './ChatApp.css';

type MessageType = 'sent' | 'received' | 'system' | 'error';

interface ChatMessage {
    msg: string;
    type: MessageType;
    time: string;
    username?: string;
    img?: string;
}

interface LocationState {
    state: {
        item: {
            name: string;
            img: string;
        }
    }
}

interface ChatProps {
    data: {
        img: string;
    }
}

const MessageItem = React.memo(({ message, isOwnMessage }: { message: ChatMessage; isOwnMessage: boolean }) => {
    return (
        <div className={`message-item ${isOwnMessage ? 'own-message' : ''}`}>
            {message.type !== 'system' && (
                <div className="avatar">
                    {message.img && (
                        <img 
                            src={message.img} 
                            alt={`${message.username}'s avatar`}
                        />
                    )}
                </div>
            )}

            <div className="message-content">
                {message.type === 'system' ? (
                    <div className="system-message">
                        {message.msg}
                    </div>
                ) : (
                    <div className={`message-bubble ${isOwnMessage ? 'own-message' : 'other-message'}`}>
                        <div>{message.msg}</div>
                        <div className={`message-time ${isOwnMessage ? 'own-message' : 'other-message'}`}>
                            {message.time}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
});

const Chatapp: React.FC<ChatProps> = () => {
    const location = useLocation() as LocationState;
    const { state: { item } } = location;
    const messageContainerRef = useRef<HTMLDivElement>(null);
    
    const [inputValue, setInputValue] = useState<string>('');
    const [messages, setMessages] = useState<ChatMessage[]>([]);
    const [socket, setSocket] = useState<Socket | null>(null);
    const [loginUsername, setLoginUsername] = useState<string>('');
    const [loginImg, setLoginImg] = useState<string>('');
    const [isSending, setIsSending] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const handleSend = async () => {
        if (!inputValue.trim() || !socket) return;
        
        try {
            setIsSending(true);
            setError(null);
            
            const messageData = {
                msg: inputValue,
                username: loginUsername,
                img: loginImg,
                type: 'sent' as MessageType,
                time: new Date().toLocaleTimeString()
            };
            
            socket.emit('message', messageData, (error: any) => {
                if (error) {
                    setError('消息发送失败，请重试');
                    console.error('Message send error:', error);
                }
            });
            
            setInputValue('');
        } catch (err) {
            setError('发送消息时发生错误');
            console.error('Send message error:', err);
        } finally {
            setIsSending(false);
        }
    };

    useEffect(() => {
        const newSocket = io('http://localhost:3001');
        setSocket(newSocket);

        newSocket.on('connect', () => {
            newSocket.emit("login", item.name, item.img);
        });

        newSocket.on('loginSuccess', (username: string, img: string) => {
            setLoginUsername(username);
            setLoginImg(img);
        });

        newSocket.on('loginError', (error: { message: string }) => {
            setMessages(prev => [...prev, {
                msg: error.message,
                type: 'error' as MessageType,
                time: new Date().toLocaleTimeString()
            }]);
        });

        newSocket.on('receiveMessage', (data: ChatMessage) => {
            const messageData: ChatMessage = {
                ...data,
                time: new Date().toLocaleTimeString(),
                type: data.username === loginUsername ? 'sent' : 'received'
            };
            setMessages(prev => [...prev, messageData]);
        });

        return () => {
            newSocket.disconnect();
        };
    }, [item.name, item.img, loginUsername]);

    // 添加滚动到底部的函数
    const scrollToBottom = () => {
        if (messageContainerRef.current) {
            messageContainerRef.current.scrollTo({
                top: messageContainerRef.current.scrollHeight,
                behavior: 'auto' // 直接到底部
            });
        }
    };

    // 监听消息变化时滚动
    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    // 监听窗口大小变化时滚动
    useEffect(() => {
        const handleResize = () => {
            scrollToBottom();
        };

        window.addEventListener('resize', handleResize);
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    // 组件挂载时滚动到底部
    useEffect(() => {
        scrollToBottom();
    }, []);

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            handleSend();
        }
    };

    const messageList = useMemo(() => {
        return messages.map((msg, index) => (
            <MessageItem
                key={index}
                message={msg}
                isOwnMessage={msg.username === loginUsername}
            />
        ));
    }, [messages, loginUsername]);

    return (
        <div className="chat-container">
            {error && (
                <div className="error-message">
                    {error}
                </div>
            )}
            
            <div 
                ref={messageContainerRef}
                className="message-container"
            >
                {messageList}
            </div>

            <div className="input-container">
                <div className="input-wrapper">
                    <span style={{ color: '#999' }}>📎</span>
                    <Input
                        placeholder="你想问什么？"
                        value={inputValue}
                        onChange={val => setInputValue(val)}
                        onKeyDown={handleKeyPress}
                    />
                </div>
                <button
                    onClick={handleSend}
                    disabled={isSending}
                    className="send-button"
                    aria-label="发送消息"
                >
                    <span style={{ transform: 'rotate(45deg)' }}>✈</span>
                </button>
            </div>
        </div>
    );
};

export default Chatapp;